import * as app from '../../common/utils/BaseApp'
import { deepClone } from '@/utils'
import * as ck from '../../common/utils/validater'
import * as utils from '@/utils/verify'
import { hasActionPriv } from '@/utils/perm'
import * as elg from '../../common/utils/ElmGenerator'
import { flatArrayToTree } from '../../common/utils/ComUtil'
import { decrypt, encrypt } from '@/utils/keygen'
import store from '@/store'

import { getOrgList } from '@/api/system/org'
import { getAllRoleList } from '@/api/system/role'
import { getAllJobTitleList } from '@/api/system/job.title'
import { getUserListByOrg, createUser, updateUser, deleteUser, updateUserStatus, getUserPassword, changeUserPassword } from '@/api/system/user'
import langFile from './user.lang'
const base = app.install({ langObj: langFile })
const pageMode = {
  add: 'add',
  detailAdd: 'detailAdd',
  update: 'update'
}
export default {
  mixins: [base],
  data() {
    return {
      formObj: {
        orgTreeData: {
          data: [],
          selectedNode: null
        },
        searchForm: {
          // ----------------------- 用户查询条件 ---------------------
          user: {
            loginName: '',
            userName: '',
            status: '',
            email: ''
          },
          likeSearch: {
            user: ['loginName', 'userName', 'email']
          }
        },
        addForm: {
          // ----------------------- 用户Form结构 ---------------------
          user: {
            id: undefined,
            loginName: '',
            userName: '',
            status: '1',
            avatar: '',
            fileName: '', // 上传文件名
            email: '',
            telNo: '',
            memo: '',
            jobtitles: [], // 工作岗位
            roles: [], // 角色
            orgs: [] // 所属组织
          },
          changePwd: {
            id: undefined,
            loginName: '',
            userName: '',
            oldPassword: '',
            newPassword: '',
            newPassword2: ''
          },
          passwordType: {
            oldPwd: 'password',
            pwd1: 'password',
            pwd2: 'password'
          },
          showFlg: {
            user: false,
            changePwd: false
          },
          showMode: {
            user: ''
          },
          jobtitleList: [],
          roleList: []
        }
      },
      listObj: {
        // ----------------------- 用户列表 ---------------------
        user: {
          ...base.$gcom.getDefListObj()
        }
      }
    }
  },
  computed: {
    isAddUser() {
      return this.formObj.addForm.showMode.user === pageMode.add ||
              this.formObj.addForm.showMode.user === pageMode.detailAdd
    },
    userSearchFormLayout() {
      const formItems = [
        elg.createInput(this, { bindId: 'loginName', propsOpt: { width: 130 }}),
        elg.createInput(this, { bindId: 'userName', propsOpt: { width: 130 }}),
        elg.createSelect(this, { bindId: 'status', optionList: elg.createChildOption(this.$dictObj['sys_valid_flg'].dict), propsOpt: { width: 120 }}),
        elg.createInput(this, { bindId: 'email', propsOpt: { width: 160 }}),
        hasActionPriv(['sys:user:query']) === false ? null
          : elg.createButton(this, this.handleSearchUser, { langId: 'search', actionValid: true, propsOpt: { icon: 'el-icon-search' }}),
        elg.createBR(),
        hasActionPriv(['sys:user:add']) === false ? null
          : elg.createButton(this, this.handleAddUser, { langId: 'add', propsOpt: { icon: 'el-icon-edit' }})
      ]
      const rules = {
        loginName: [
          ck.createMaxLenValidater(this, 20)
        ],
        userName: [
          ck.createMaxLenValidater(this, 50)
        ],
        email: [
          ck.createMaxLenValidater(this, 50)
        ]
      }
      return { formItems: formItems, rules: rules }
    },
    userAddFormLayout() {
      const _target = this.formObj.addForm.user
      const isAdmin = _target.adminFlg === '1'
      let statusList = deepClone(this.$dictObj['sys_valid_flg'].dict)
      if (isAdmin) {
        _target.status = '1'
        statusList = statusList.map((item) => {
          item['disabled'] = item.id !== '1'
          return item
        })
      }
      const formItems = [
        elg.createInput(this, { bindId: 'loginName', isDisabled: isAdmin }),
        elg.createInput(this, { bindId: 'userName' }),
        elg.createSelectTree(this, { bindId: 'orgs', treeData: this.formObj.orgTreeData.data, propsOpt: { multiple: true }}),
        elg.createAvatarUpload(this, { bindImgId: 'avatar', bindImgName: 'fileName', uploadUrl: 'md_sys_upload/uploadAvatarFile' }),
        elg.createRadioGroup(this, { bindId: 'status', optionList: elg.createChildRadio(statusList) }),
        elg.createInput(this, { bindId: 'email' }),
        elg.createInput(this, { bindId: 'telNo' }),
        elg.createSelect(this, { bindId: 'jobtitles', optionList: elg.createChildOption(this.formObj.addForm.jobtitleList),
          propsOpt: { width: 160, multiple: true, filterable: true }}),
        elg.createSelect(this, { bindId: 'roles', optionList: elg.createChildOption(this.formObj.addForm.roleList),
          propsOpt: { width: 160, multiple: true, filterable: true }}),
        elg.createTextArea(this, { bindId: 'memo' })
      ]
      const footerItems = [
        hasActionPriv(['sys:user:add', 'sys:user:update']) === false ? null
          : elg.createButton(this, this.handleSaveUser, { langId: 'confirm', actionValid: true, propsOpt: { icon: '' }})
      ]
      const rules = {
        loginName: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 20), ck.createUndlineEngNumWordValidater(this)
        ],
        userName: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 50)
        ],
        avatar: [
          ck.createRequiredValidater(this)
        ],
        status: [
          ck.createRequiredValidater(this)
        ],
        email: [
          ... (isAdmin ? [ck.createEMailValidater(this)] : [ck.createRequiredValidater(this), ck.createEMailValidater(this)])
        ],
        telNo: [
          ck.createTelphoneOrMobileValidater(this)
        ],
        jobtitles: [
          ... (isAdmin ? [] : [ck.createRequiredValidater(this)])
        ],
        memo: [
          ck.createMaxLenValidater(this, 255)
        ]
      }
      return { formItems: formItems, footerItems: footerItems, rules: rules }
    },
    userListLayout() {
      const itemColumns = [
        elg.createTableColumn(this, { bindId: 'loginName', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'userName', align: 'center' }),
        elg.createTableColumn(this, {
          bindId: elg.createSwitch(this, { bindId: 'status', context: { active: this.$dictObj['sys_valid_flg'].dict[0], inactive: this.$dictObj['sys_valid_flg'].dict[1] }}),
          formatter: {
            disableFnc: (row, v) => {
              return row.adminFlg === '1' || hasActionPriv(['sys:user:change_status']) === false
            }
          },
          action: {
            change: (row, name) => {
              this.$showConfirm({ msg: this.getLang('message.rule.changeStatusConfirm'),
                ok: async() => {
                  await updateUserStatus(row)
                },
                ng: () => {
                  row[name] === '1' ? row[name] = '2' : row[name] = '1'
                } })
            } },
          align: 'left' }),
        elg.createTableColumn(this,
          { bindId: elg.createImgViewer(this, { bindImgUrl: 'fileName', bindImgSize: { width: '25', height: '25' }, langId: 'avatar', propsOpt: { width: 90 }}),
            align: 'center' }),
        elg.createTableColumn(this, { bindId: 'email', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'memo', align: 'center' })
      ]
      const actionColumns = [
        hasActionPriv(['sys:user:change_pwd']) === false ? null
          : elg.createTableAction(this, { langId: 'updatePwd', actionFnc: this.handleUpdatePwd }),
        hasActionPriv(['sys:user:update']) === false ? null
          : elg.createTableAction(this, { langId: 'edit', actionFnc: this.handleUpdateUser }),
        hasActionPriv(['sys:user:delete']) === false ? null
          : elg.createTableAction(this, { langId: 'delete', actionFnc: this.handleDeleteUser, visableFnc: (row, index) => {
            return (row.adminFlg !== '1')
          } })
      ]
      return { columns: itemColumns, actions: actionColumns }
    },
    userChangePwdFormLayout() {
      const formItems = [
        elg.createInput(this, { bindId: 'userName', isDisabled: true, propsOpt: { width: '100%' }}),
        // elg.createInput(this, { bindId: 'oldPassword', isDisabled: true, propsOpt: { width: '100%', class: this.formObj.addForm.passwordType.oldPwd }}),
        elg.createInput(this, { bindId: 'newPassword', isDisabled: false, propsOpt: { width: '100%', class: this.formObj.addForm.passwordType.pwd1 }}),
        elg.createBlank(),
        elg.createInput(this, { bindId: 'newPassword2', isDisabled: false, propsOpt: { width: '100%', class: this.formObj.addForm.passwordType.pwd2 }})
      ]
      const footerItems = [
        elg.createButton(this, this.handleSavePwd, { langId: 'confirm', actionValid: true, propsOpt: { icon: '' }})
      ]
      const rules = {
        newPassword: [ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 50), ck.createCustomValidater(this, this.pwdIsSameValidator)],
        newPassword2: [ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 50), ck.createCustomValidater(this, this.pwdIsSameValidator)]
      }
      return { formItems: formItems, footerItems: footerItems, rules: rules }
    }
  },
  async created() {
    this.$gcom.formObj = deepClone(this.formObj)
    await this.searchOrgList()
    // 根据选中组织查询所属用户
    await this.searchUserList()
    // 工作岗位查询
    await this.searchAllJobTitleList()
    // 角色查询
    await this.searchAllRoleList()
  },
  methods: {
    async searchAllJobTitleList() {
      const result = await getAllJobTitleList()
      this.formObj.addForm.jobtitleList = result.data.listLine.map((item) => {
        return { id: item.jobtitleId, name: item.jobtitleName }
      })
    },
    async searchAllRoleList() {
      const result = await getAllRoleList()
      this.formObj.addForm.roleList = result.data.listLine.map((item) => {
        return { id: item.roleId, name: item.roleName }
      })
    },
    // ----------------------- 组织架构查询 ---------------------
    async searchOrgList() {
      const result = await getOrgList()
      const orgList = result.data.listLine.map((item) => {
        return { id: item.orgId, name: item.orgName, parentId: item.parentId }
      })
      const _target = this.formObj.orgTreeData
      _target.data = flatArrayToTree(orgList, { exclude: [] })
      if (_target.data.length > 0) {
      // 默认选中节点第一个，node-key： 每个树节点用来作为唯一标识的属性
        _target.selectedNode = _target.data[0]
      }
    },
    // 组织节点单击事件
    async handleTreeNodeClick(node) {
      const _target = this.formObj.orgTreeData
      _target.selectedNode = node
      // 根据选中组织查询所属用户
      await this.searchUserList()
    },
    // ----------------------- 用户列表查询 ---------------------
    async searchUserList() {
      let searchForm = {}
      if (this.formObj.orgTreeData.selectedNode !== null) {
        // 根据选中组织查询所属用户
        searchForm = { orgId: this.formObj.orgTreeData.selectedNode.id }
      }

      const _target = this.listObj.user
      try {
        _target.listLineLoading = true
        searchForm = { ...searchForm, ... this.formObj.searchForm.user }
        const result = await getUserListByOrg({
          searchForm: searchForm,
          likeSearch: this.formObj.searchForm.likeSearch.user,
          pagingDefine: this.listObj.user.pagingDefine
        })

        _target.listLine = result.data.listLine
        _target.lineNum = result.data.lineNum
      } catch (err) {
        console.log(err)
      } finally {
        setTimeout(() => {
          _target.listLineLoading = false
        }, 0)
      }
    },
    // ----------------------- 用户列表查询 ---------------------
    handleSearchUser() {
      this.validateAll(['searchForm'], () => {
        this.listObj.user.pagingDefine.page = 1
        this.searchUserList()
      })
    },
    handleAddUser(row, index) {
      this.openDialog('user', pageMode.add)
    },
    handleUpdateUser(row, index) {
      this.openDialog('user', pageMode.update, row)
    },
    // ----------------------- 用户保存 ---------------------
    handleSaveUser() {
      this.validateAll(['userEditDlg'], async() => {
        if (this.isAddUser) {
          await createUser(this.formObj.addForm.user)
        } else {
          await updateUser(this.formObj.addForm.user)
        }
        if (store.getters.loginName === this.formObj.addForm.user.loginName) {
          // 如果是当前登录用户，刷新头像
          await this.$store.dispatch('user/setAvatar', this.formObj.addForm.user.fileName)
        }
        this.searchUserList()
        this.formObj.addForm.showFlg.user = false
      })
    },
    async handleDeleteUser(row, index) {
      this.$showConfirm({ msg: this.getLang('message.rule.deleteUserConfirm'), ok: async() => {
        await deleteUser(row.id)
        setTimeout(async() => {
          this.listObj.user.pagingDefine.page = 1
          this.searchUserList()
        }, 500)
      } })
    },
    // ----------------------- 修改密码 ---------------------
    async handleUpdatePwd(row, index) {
      const result = await getUserPassword({ searchForm: { id: row.id }})
      this.formObj.addForm.changePwd.id = result.data.listLine[0].id
      this.formObj.addForm.changePwd.loginName = result.data.listLine[0].loginName
      this.formObj.addForm.changePwd.userName = result.data.listLine[0].userName
      this.formObj.addForm.changePwd.oldPassword = decrypt(result.data.listLine[0].oldPassword)
      this.formObj.addForm.changePwd.newPassword = ''
      this.formObj.addForm.changePwd.newPassword2 = ''
      this.formObj.addForm.passwordType.oldPwd = 'no-autofill-pwd'
      this.formObj.addForm.passwordType.pwd1 = 'no-autofill-pwd'
      this.formObj.addForm.passwordType.pwd2 = 'no-autofill-pwd'

      this.formObj.addForm.showFlg.changePwd = true
    },
    showPwd(key) {
      const _target = this.formObj.addForm.passwordType
      _target[key] === 'no-autofill-pwd' ? _target[key] = '' : _target[key] = 'no-autofill-pwd'
    },
    handleSavePwd() {
      this.validateAll(['changePwdDlg'], async() => {
        const _target = this.formObj.addForm.changePwd
        await changeUserPassword({ loginName: _target.loginName,
          password: encrypt(_target.newPassword.trim()),
          password2: encrypt(_target.newPassword2.trim()) })
        this.formObj.addForm.showFlg.changePwd = false
      })
    },
    // ----------------------- 密码一致Check ---------------------
    pwdIsSameValidator(rule, value, callback) {
      const _target = this.formObj.addForm.changePwd
      if (utils.isContainsVal(_target.newPassword.trim()) && utils.isContainsVal(_target.newPassword2.trim())) {
        const isSame = _target.newPassword.trim() === _target.newPassword2.trim()
        if (!isSame) {
          callback(new Error(this.getLang('message.rule.pwdNotSame')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    // ----------------------- Open Dialog ---------------------
    openDialog(target, mode, row, index) {
      const data = row === undefined ? this.$gcom.formObj.addForm[target] : row
      this.formObj.addForm[target] = { ...data }
      this.formObj.addForm.showFlg[target] = true
      this.formObj.addForm.showMode[target] = mode
    }
  }
}
